package com.gdssoft.pdaweb.action.water;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.BeanUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.util.DateUtil;
import com.gdssoft.core.util.JsonUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.pdaweb.model.PdaMdBuilding;
import com.gdssoft.pdaweb.model.PdaMdDistrict;
import com.gdssoft.pdaweb.model.PdaMdHouse;
import com.gdssoft.pdaweb.model.water.PdaWaterMeter;
import com.gdssoft.pdaweb.model.water.WaterMeterMonthPlan;
import com.gdssoft.pdaweb.model.water.WaterMeterMonthPlanRead;
import com.gdssoft.pdaweb.model.water.WaterMeterPlan;
import com.gdssoft.pdaweb.service.PdaMdBuildingService;
import com.gdssoft.pdaweb.service.PdaMdDistrictService;
import com.gdssoft.pdaweb.service.PdaMdHouseService;
import com.gdssoft.pdaweb.service.water.PdaWaterMeterService;
import com.gdssoft.pdaweb.service.water.WaterMeterMonthPlanService;
import com.gdssoft.pdaweb.service.water.WaterMeterPlanService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ibm.icu.text.SimpleDateFormat;

import flexjson.JSONSerializer;

public class WaterMeterPlanAction extends BaseAction {
	@Resource
	private WaterMeterPlanService waterMeterPlanService;

	private WaterMeterPlan waterMeterPlan;

	private Long planId;

	@Resource
	private WaterMeterMonthPlanService waterMeterMonthPlanService;

	@Resource
	private PdaWaterMeterService pdaWaterMeterService;

	@Resource
	private PdaMdDistrictService pdaMdDistrictService;

	@Resource
	private PdaMdBuildingService pdaMdBuildingService;
	

	@Resource
	private PdaMdHouseService pdaMdHouseService;

	public PdaMdBuildingService getPdaMdBuildingService() {
		return pdaMdBuildingService;
	}

	public void setPdaMdBuildingService(
			PdaMdBuildingService pdaMdBuildingService) {
		this.pdaMdBuildingService = pdaMdBuildingService;
	}

	public PdaMdDistrictService getPdaMdDistrictService() {
		return pdaMdDistrictService;
	}

	public void setPdaMdDistrictService(
			PdaMdDistrictService pdaMdDistrictService) {
		this.pdaMdDistrictService = pdaMdDistrictService;
	}

	public PdaWaterMeterService getPdaWaterMeterService() {
		return pdaWaterMeterService;
	}

	public void setPdaWaterMeterService(
			PdaWaterMeterService pdaWaterMeterService) {
		this.pdaWaterMeterService = pdaWaterMeterService;
	}

	public WaterMeterMonthPlanService getWaterMeterMonthPlanService() {
		return waterMeterMonthPlanService;
	}

	public void setWaterMeterMonthPlanService(
			WaterMeterMonthPlanService waterMeterMonthPlanService) {
		this.waterMeterMonthPlanService = waterMeterMonthPlanService;
	}

	public WaterMeterPlanService getWaterMeterPlanService() {
		return waterMeterPlanService;
	}

	public void setWaterMeterPlanService(
			WaterMeterPlanService waterMeterPlanService) {
		this.waterMeterPlanService = waterMeterPlanService;
	}

	public WaterMeterPlan getWaterMeterPlan() {
		return waterMeterPlan;
	}

	public void setWaterMeterPlan(WaterMeterPlan waterMeterPlan) {
		this.waterMeterPlan = waterMeterPlan;
	}

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	/**
	 * 显示列表
	 */
	public String list() {
		QueryFilter filter = new QueryFilter(getRequest());
		filter.addSorted("planStatus", QueryFilter.ORDER_DESC);
		filter.addSorted("planName", QueryFilter.ORDER_ASC);
		List<WaterMeterPlan> list = waterMeterPlanService.getAll(filter);
		
		int toDayDate = Calendar.getInstance().get(Calendar.DATE);
		String thisMonth = DateUtil.dateFormat(new Date(), "yyyy-MM");
		WaterMeterMonthPlan monthPlan = null;
		for(WaterMeterPlan p :list){
			if(toDayDate > Integer.parseInt(p.getAccountDay())){	//过了月结日
				p.setPlanStatus(0L);
			}else{
				monthPlan = waterMeterMonthPlanService.getByPlanIdAndMonth(p.getPlanId(),thisMonth);
				if(monthPlan != null && monthPlan.getPlanStatus()==0L){
					//当状态是执行过的，设置为2
					p.setPlanStatus(2L);
				}
			}
		}
		
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(filter.getPagingBean().getTotalItems()).append(
						",result:");
		Type type = new TypeToken<List<WaterMeterPlan>>(){}.getType();
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.setDateFormat("yyyy-MM-dd").create();
		buff.append(gson.toJson(list, type));

		buff.append("}");
		jsonString = buff.toString();

		return SUCCESS;
	}

	/**
	 * 批量删除
	 * 
	 * @return
	 */

	public String multiDel() {

		String[] ids = getRequest().getParameterValues("ids");
		if (ids != null) {
			for (String id : ids) {
				try {
					this.waterMeterPlanService.remove(new Long(id));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 显示详细信息
	 * 
	 * @return
	 */
	public String get() {
		// deviceId =
		// Long.parseLong(getRequest().getParameterValues("deviceId")[0]);
		// DeviceReg deviceReg=deviceRegService.get(deviceId);
		// //Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd").create();
		// Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		// //将数据转成JSON格式
		// StringBuffer sb = new StringBuffer("{success:true,data:");
		// sb.append(gson.toJson(deviceReg));
		// sb.append("}");
		//
		// setJsonString(sb.toString());
		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 */
	public String save() {
		
		String removedStr = getRequest().getParameter("removed");
		String[] removeds = {};
		if(!removedStr.trim().isEmpty()){
			removeds = removedStr.split(",");
		}		
		String amIdss = getRequest().getParameter("selectedIds");
		String[] amIds = {};
		if(!amIdss.trim().isEmpty()){
			amIds = amIdss.split(",");
		}
		
		
		boolean success = true;
		if (amIdss.length() == 0) {
			success = false;
		} else {
			String un = ContextUtil.getCurrentUser().getUsername();
			Date now = new Date();
			if (waterMeterPlan.getPlanId() == null) {
				waterMeterPlan.setCreatedby(un);
				waterMeterPlan.setCreateddt(now);
				waterMeterPlan.setPlanStatus((long) 0);
			}else{
				WaterMeterPlan plan = waterMeterPlanService.get(waterMeterPlan
						.getPlanId());
				try {
					BeanUtil.copyNotNullProperties(plan, waterMeterPlan);
				} catch (Exception e) {
					success = false;
					e.printStackTrace();
				}
				waterMeterPlan = plan;
				waterMeterPlan.setLastEditDt(now);
				waterMeterPlan.setLastEditBy(un);
			}
			waterMeterPlan.setMeterCount(new Long(amIds.length));
			try {
				waterMeterPlanService.save(waterMeterPlan, amIds, removeds);
			} catch (Exception e) {
				success = false;
				e.printStackTrace();
			}
		}
		setJsonString("{success:" + success + "}");
		return SUCCESS;
	}

	/**
	 * 执行计划
	 */
	public String execute() {
		String username = getRequest().getParameter("username");
		String planId = getRequest().getParameter("planId");
		String beginTime = getRequest().getParameter("beginTime");
		String endTime = getRequest().getParameter("endTime");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date beginTime2 = new Date();
		Date endTime2 = new Date();
		try {
			beginTime2 = sdf.parse(beginTime);
			endTime2 = sdf.parse(endTime);
		} catch (ParseException e) {
			logger.debug("日期转换出错,beginTime:" + beginTime + ",endTime:"
					+ endTime);
			e.printStackTrace();
		}

		boolean res = waterMeterPlanService.execute(Long.parseLong(planId),
				beginTime2, endTime2, username);

		jsonString = "{success:" + res + "}";

		return SUCCESS;
	}

	/**
	 * 显示抄表人姓名
	 */
	public String showExecutorName() {

		List<AppUser> ls = waterMeterPlanService.getExecutor();
		StringBuffer buff = new StringBuffer("[");
		for (AppUser appUser : ls) {
			buff.append("[\"" + appUser.getUsername() + "\",\""
					+ appUser.getFullname() + "(" + appUser.getUsername()
					+ ")\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}

	/**
	 * 通过Id获取相应的水表号
	 */
	public String getByPlanId() {
		List<String> amIds = waterMeterPlanService.getByPlanId(planId);
		StringBuffer buff = new StringBuffer("[");
		for (String id : amIds) {
			buff.append("[\"" + id + "\",\"" + id + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");
		setJsonString(buff.toString());

		return SUCCESS;
	}

	/**
	 * 显示水表编号
	 */
	public String getWaterMeterId() {
		String districtId = getRequest().getParameter("districtId");
		String buildingId = getRequest().getParameter("buildingId");
		List<PdaWaterMeter> ls = pdaWaterMeterService.getWaterMeter(districtId,
				buildingId);
		if (ls.size() > 0) {
			StringBuffer buff = new StringBuffer("[");
			for (PdaWaterMeter pdaWaterMeter : ls) {
				buff.append("[\"" + pdaWaterMeter.getAmId() + "\",\""
						+ pdaWaterMeter.getAmId() + "\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]");
			setJsonString(buff.toString());
		} else {
			setJsonString("[]");
		}
		return SUCCESS;
	}

	/**
	 * 查看任务
	 */
	public String checkTask() {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

		String planId = getRequest().getParameter("planId");
		String month = getRequest().getParameter("month");

		List<WaterMeterMonthPlanRead> ls = waterMeterPlanService.getPlanTask(
				Long.parseLong(planId), month);

		StringBuffer buff = new StringBuffer("{success:true,'result':");

		JSONSerializer json = JsonUtil.getJSONSerializer();
		buff.append(json.exclude(
				new String[] { "class", "WaterMeterMonthPlanRead" }).serialize(
				ls));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 显示区号信息
	 */
	public String showDistrict() {
		List<PdaMdDistrict> ls = pdaMdDistrictService.getAll();
		StringBuffer buff = new StringBuffer("[");
		for (PdaMdDistrict pdaMdDistrict : ls) {
			buff.append("[\"" + pdaMdDistrict.getDistrictId() + "\",\""
					+ pdaMdDistrict.getDistrictName() + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());
		return SUCCESS;
	}

	/**
	 * 显示栋号信息
	 */
	public String showBuilding() {
		String districtId = getRequest().getParameter("districtId");
		List<PdaMdBuilding> ls = pdaMdBuildingService
				.getByDistrictId(districtId);

		StringBuffer buff = new StringBuffer("[");
		for (PdaMdBuilding pdaMdBuilding : ls) {
			buff.append("[\"" + pdaMdBuilding.getBuildingId() + "\",\""
					+ pdaMdBuilding.getBuildingName() + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}
	
	/**
	 * 显示房间信息
	 */
	public String showHouse() {
		String buildingId = getRequest().getParameter("buildingId");
		QueryFilter filter = new QueryFilter();
		filter.addFilter("Q_buildingId_S_EQ", buildingId);
		List<PdaMdHouse> ls = pdaMdHouseService.getAll(filter);
		StringBuffer buff = new StringBuffer("[");
		for (PdaMdHouse pdaMdHouse : ls) {
			buff.append("[\"" + pdaMdHouse.getHouseId() + "\",\""
					+ pdaMdHouse.getName()+ "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}

}
